import { dialog, screen } from 'electron';
import { getMainWindow } from 'ee-core/electron';
import { BrowserWindow } from 'electron';

/**
 * effect - demo
 * @class
 */
class EffectController {

  /**
   * select file
   */
  selectFile(): string | null {
    const filePaths = dialog.showOpenDialogSync({
      properties: ['openFile']
    });

    if (!filePaths) {
      return null
    }

    return filePaths[0];
  }

  /**
   * login window
   */
  loginWindow(args: { width?: number; height?: number }): void {
    const { width, height } = args;
    const win = getMainWindow();
    
    const size = {
      width: width || 400,
      height: height || 300
    }
    win.setSize(size.width, size.height);
    win.setResizable(true);
    win.center();
    win.show();
    win.focus();
  }
  
  /**
   * restore window
   */
  restoreWindow(args: { width?: number; height?: number }): void {
    const { width, height } = args;
    const win = getMainWindow();

    const size = {
      width: width || 980,
      height: height || 650
    }
    win.setSize(size.width, size.height);
    win.setResizable(true);
    win.center();
    win.show();
    win.focus();
  }
  
  /**
   * Show animated GIF when entering work start/end times
   */
  showWorkTimeGif(args: { 
    startTime: string; 
    endTime: string; 
    startDateTime: number;
    endDateTime: number;
    totalDurationMs: number;
    elapsedMs: number;
    speedMode?: 'realtime' | 'hourly' | 'accelerated'
  }): boolean {
    try {
      const win = getMainWindow();
      const { 
        startTime, 
        endTime, 
        startDateTime,
        endDateTime,
        totalDurationMs,
        elapsedMs,
        speedMode = 'realtime'
      } = args;
      
      // Create a new transparent window for the GIF
      const gifWindow = new BrowserWindow({
        width: 300,
        height: 120,
        frame: false,
        transparent: true,
        alwaysOnTop: true,
        resizable: false,
        movable: false,
        hasShadow: false,
        webPreferences: {
          nodeIntegration: true,
          contextIsolation: false
        }
      });
      
      // Position the window at the left edge, vertically centered
      const primaryDisplay = screen.getPrimaryDisplay();
      const { width, height } = primaryDisplay.workAreaSize;
      
      // Calculate initial position based on elapsed time
      const progress = elapsedMs / totalDurationMs;
      const initialPosition = Math.floor(width * progress);
      gifWindow.setPosition(initialPosition, Math.floor(height / 2) - 50);
      
      // Load the HTML content for the GIF
      const path = require('path');
      const htmlPath = path.join(__dirname, '../../public/html/gif-display.html');
      gifWindow.loadFile(htmlPath);
      
      // Pass data to the window
      gifWindow.webContents.once('dom-ready', () => {
        gifWindow.webContents.send('work-time-data', { 
          startTime,
          endTime,
          startDateTime,
          endDateTime,
          totalDurationMs,
          elapsedMs,
          speedMode
        });
      });
      
      // Calculate animation parameters based on speed mode
      let animationDuration: number;
      switch (speedMode) {
        case 'hourly':
          // Animate over 1 hour regardless of actual work duration
          animationDuration = 60 * 60 * 1000;
          break;
        case 'accelerated':
          // Animate over 5 minutes regardless of actual work duration
          animationDuration = 5 * 60 * 1000;
          break;
        case 'realtime':
        default:
          // Animate over actual remaining duration, but capped for visibility
          animationDuration = Math.min(totalDurationMs - elapsedMs, 300000); // Max 5 minutes
          break;
      }
      
      // Calculate end position accounting for window width
      const endPosition = width - 300;
      
      // If work time has already ended, show completion
      const remainingDuration = totalDurationMs - elapsedMs;
      if (remainingDuration <= 0) {
        gifWindow.setPosition(endPosition, Math.floor(height / 2) - 50);
        setTimeout(() => {
          gifWindow.close();
        }, 5000);
        return true;
      }
      
      // Calculate animation parameters
      const totalTimeSeconds = animationDuration / 1000;
      const startPosition = initialPosition;
      const totalDistance = endPosition - startPosition;
      const pixelsPerSecond = totalDistance / totalTimeSeconds;
      
      // Update position every 50ms for smooth animation
      const updateInterval = 50;
      const pixelsPerInterval = pixelsPerSecond * (updateInterval / 1000);
      
      const moveInterval = setInterval(() => {
        // Check if work time has ended
        const now = Date.now();
        if (now >= endDateTime) {
          // Move to final position and stop
          gifWindow.setPosition(endPosition, Math.floor(height / 2) - 50);
          clearInterval(moveInterval);
          // Keep window open for a while to show it has finished
          setTimeout(() => {
            gifWindow.close();
          }, 5000);
          return;
        }
        
        // Move window based on elapsed time
        let newPosition = startPosition + (now - startDateTime) * (totalDistance / totalDurationMs);
        if (speedMode !== 'realtime') {
          // For non-realtime modes, calculate position based on animation duration
          const elapsedAnimationTime = Math.min(now - (startDateTime + elapsedMs), animationDuration);
          const animationProgress = elapsedAnimationTime / animationDuration;
          newPosition = startPosition + (animationProgress * totalDistance);
        }
        
        if (newPosition < endPosition) {
          gifWindow.setPosition(Math.floor(newPosition), Math.floor(height / 2) - 50);
        } else {
          gifWindow.setPosition(endPosition, Math.floor(height / 2) - 50);
        }
      }, updateInterval);
      
      // Also close the window after animation duration if work time hasn't ended
      setTimeout(() => {
        if (!gifWindow.isDestroyed()) {
          clearInterval(moveInterval);
          gifWindow.close();
        }
      }, animationDuration + 5000);
      
      return true;
    } catch (error) {
      console.error('Error showing work time GIF:', error);
      return false;
    }
  }
}

export default new EffectController();